import { defineStore } from "pinia";
import { ref } from "vue";
import { deepMerge, storage } from "../../utils";
import { router } from "../router";
import { service } from "../service";

// 本地缓存
const data = storage.info();

const useUserStore = defineStore("user", function () {
	// 标识
	const token = ref<any>(storage.get('token') || '');

	async function login(refresh?: boolean) {
		// const code = uni.getStorageSync('loginCode') || '111'
		console.info("router", router.query)
		const code = router.query?.authCode ?? null
		if (!code && token.value) return true
		
		let bizType = 'DINING_ROOM'
		if ((router.path?.indexOf('/pages/mess/') ?? -1) > -1) {
			bizType = 'DINING_ROOM'
		} else if ((router.path?.indexOf('/pages/fitness/') ?? -1) > -1) {
			bizType = 'KEEP'
		} else if ((router.path?.indexOf('/pages/farm/') ?? -1) > -1) {
			bizType = 'FARM'
		} else if ((router.path?.indexOf('/pages/activity/') ?? -1) > -1) {
			bizType = 'ACTIVITY'
		} else if ((router.path?.indexOf('/pages/integral/') ?? -1) > -1) {
			bizType = 'INTEGRAL_MALL'
		}

		const data = await service.common.login({ code, bizType })
		setToken(data)

		return data
	}

	// 设置标识
	// function setToken({ accessToken, accessTokenExpires, refreshToken, refreshTokenExpires }: any) {
	// 	token.value = accessToken;

	// 	// 访问
	// 	storage.set("token", accessToken, accessTokenExpires - 5);
	// 	// 刷新
	// 	storage.set("refreshToken", refreshToken, refreshTokenExpires);
	// }
	function setToken(tokenStr: any) {
		token.value = tokenStr;

		// 访问
		storage.set("token", tokenStr);
		// 刷新
		// storage.set("refreshToken", refreshToken, refreshTokenExpires);
	}

	// 刷新标识
	async function refreshToken() {
		return service.user.login
			.refreshToken({
				refreshToken: storage.get("refreshToken"),
			})
			.then((res) => {
				setToken(res);
				return res.accessToken;
			});
	}

	// 用户信息 *****************

	const info = ref<any>(data.userInfo);
	// const info = ref<any>({});

	// 设置用户信息
	function set(value: Eps.UserInfoEntity) {
		info.value = value;
		storage.set("userInfo", value);
	}

	// 更新用户信息
	async function update(data: any) {
		set(deepMerge(info.value, data));
		await service.user.info.update(info.value);
	}

	// 清除用户
	function clear() {
		storage.remove("userInfo");
		storage.remove("token");
		storage.remove("refreshToken");
		token.value = "";
		info.value = undefined;
	}

	// 退出
	function logout() {
		clear();
		router.login({ reLaunch: true });
	}

	// 获取用户信息
	async function get(refresh?: boolean) {
		if (info.value.id && !refresh) {
			return info.value
		}

		if (!token.value || refresh) {
			await login()
		}

		return service.common.user()
			.then(async (res: any) => {
				if (res.success) {
					await set(res.data);
				}
				return res.data;
			})
			.catch(() => {
				logout();
			});
	}
	return {
		token,
		setToken,
		refreshToken,

		info,
		get,
		set,
		update,
		logout,
	};
});

export default useUserStore;
